<template>
  <div>
    <el-form
      size="small"
      :model="form"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
    >
      <el-form-item label="签到活动：" prop="isOpen">
        <el-radio v-model="form.isOpen" :label="true">开启</el-radio>
        <el-radio v-model="form.isOpen" :label="false">关闭</el-radio>
      </el-form-item>
      <div class="open-sign">
        <span class="gray9">开启后，客户可在每日签到页面进行签到</span>
      </div>
      <el-form-item label="签到模式：" prop="signType">
        <el-radio v-model="form.signType" :label="0">无限制</el-radio>
        <el-radio v-model="form.signType" :label="1">周循环</el-radio>
        <el-radio v-model="form.signType" :label="2">月循环</el-radio>
      </el-form-item>
      <div class="open-sign">
        <span class="gray9"
          >无限制，累积和连续签到不会清零，周循环，每周一会清理连续的记录为0，重新开启计算，月循环，每月一号会清理连续的记录为0，重新开启计算</span
        >
      </div>
      <div v-if="form.isOpen" class="mt16">
        <el-form-item label="每日签到：" prop="everSign">
          <div class="d-s-s d-c bg_coupon">
            <el-form-item label="赠送优惠券">
              <el-radio-group v-model="form.isCoupon">
                <el-radio :label="true">开启</el-radio>
                <el-radio :label="false">关闭</el-radio>
              </el-radio-group>
            </el-form-item>
            <div style="width: 96%" v-if="form.isCoupon == true">
              <el-table :data="couponList" style="width: 100%" class="ml20">
                <el-table-column prop="couponId" label="优惠券ID">
                </el-table-column>
                <el-table-column prop="name" label="优惠券名称">
                </el-table-column>
                <el-table-column label="赠送张数">
                  <template #default="scope">
                    <el-form-item
                      :rules="[{ required: true, message: '1-9' }, cprules]"
                      :prop="'coupon.' + scope.$index + '.couponNum'"
                    >
                      <el-input
                        type="number"
                        v-model="form.coupon[scope.$index].couponNum"
                      >
                        <template #append>张</template>
                      </el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="address" label="操作">
                  <template #default="scope">
                    <el-button
                      type="primary"
                      size="small"
                      link
                      @click="delcoupon(scope.row)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-button
                type="primary"
                @click="addCoupon('coup')"
                class="ml20"
                icon="Plus"
                >添加优惠劵</el-button
              >
            </div>
            <el-form-item label="赠送积分">
              <el-input
                v-model="form.everSign"
                placeholder="请输入赠送积分"
                type="number"
                min="0"
              >
                <template #append>积分</template></el-input
              >
            </el-form-item>
          </div>
          <div>
            <span>递增奖励</span>
            <el-radio v-model="form.isIncrease" :label="true">开启</el-radio>
            <el-radio v-model="form.isIncrease" :label="false">关闭</el-radio>
          </div>
          <div v-if="form.isIncrease" class="bg_coupon border p-0-20 pt16 mt10">
            <el-form-item
              label="第二天起递增奖励"
              label-width="120px"
              prop="increase_reward"
            >
              <div class="d-s-c">
                <div>
                  <el-input
                    v-model="form.increaseReward"
                    placeholder="请输入第二天起递增积分数"
                    style="width: 180px"
                    min="0"
                    type="number"
                  ></el-input>
                </div>
                <span class="ml10">积分</span>
              </div>
            </el-form-item>
            <el-form-item label="第" label-width="120px" prop="noIncrease">
              <div class="d-s-c">
                <div>
                  <el-input
                    v-model="form.noIncrease"
                    placeholder="请输入第几天不再递增"
                    min="0"
                    style="width: 180px"
                    type="number"
                  ></el-input>
                </div>
                <span class="ml10">天起不再递增</span>
              </div>
            </el-form-item>
          </div>
        </el-form-item>
        <div class="mt10 mb10" style="margin-left: 100px">
          <span class="gray9"
            >用户可在签到页每日签到一次，签到后可获得每日签到奖励
          </span>
        </div>
        <el-form-item label="连续签到：" prop="everSign">
          <!-- <el-radio v-model="form.isOpen" :label="true">开启</el-radio>
          <el-radio v-model="form.isOpen" :label="false">关闭</el-radio> -->
        </el-form-item>
        <div class="open-sign">
          <span class="gray9"
            >用户连续签到指定天数后会获得奖励，断签则重新计算（不重复发放日签奖励）
          </span>
        </div>
        <el-form-item label="">
          <div class="reward-list">
            <div
              class="reward-item pr border"
              v-for="(item, reward_index) in form.rewardData"
              :key="reward_index"
            >
              <el-button
                class="delete-reward"
                @click="deleteRewardClick(reward_index)"
                type="primary"
                size="small"
                link
                >删除</el-button
              >
              <span class="ml10">连续签到规则{{ reward_index + 1 }}</span>
              <el-form-item
                label="签到天数"
                :prop="'rewardData.' + reward_index + '.day'"
                :rules="rules.day"
              >
                <div class="d-s-c">
                  <div>
                    <el-input
                      v-model="item.day"
                      placeholder="请输入连续签到天数"
                      class="max-w460"
                      type="number"
                      min="0"
                      ><template #prepend>连续签到</template>
                      <template #append>天</template></el-input
                    >
                  </div>
                </div>
              </el-form-item>
              <el-form-item label="">
                <div class="d-s-s d-c">
                  <div class="ml20">
                    <el-checkbox v-model="item.isCoupon"
                      >赠送优惠劵</el-checkbox
                    >
                    <el-checkbox v-model="item.isPoint">赠送积分</el-checkbox>
                  </div>
                  <div style="width: 96%" v-if="item.isCoupon">
                    <el-table
                      :data="item.coupon"
                      style="width: 100%"
                      class="ml20"
                    >
                      <el-table-column prop="couponId" label="优惠券ID">
                      </el-table-column>
                      <el-table-column prop="name" label="优惠券名称">
                      </el-table-column>
                      <el-table-column label="赠送张数">
                        <template #default="scope">
                          <el-form-item
                            :rules="[
                              { required: true, message: '1-9' },
                              cprules,
                            ]"
                            :prop="'coupon.' + scope.$index + '.couponNum'"
                          >
                            <el-input
                              type="number"
                              v-model="item.coupon[scope.$index].couponNum"
                            >
                              <template #append>张</template>
                            </el-input>
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column prop="address" label="操作">
                        <template #default="scope">
                          <el-button
                            type="primary"
                            size="small"
                            link
                            @click="delcoupons(reward_index, scope.$index)"
                          >
                            删除
                          </el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                    <el-button
                      type="primary"
                      @click="addCoupon('coup_sum', reward_index)"
                      class="ml20"
                      icon="Plus"
                      >添加优惠劵</el-button
                    >
                  </div>
                  <el-form-item label="赠送积分" v-if="item.isPoint">
                    <el-input
                      v-model="item.point"
                      placeholder="请输入赠送积分"
                      type="number"
                      min="0"
                      style="width: 200px"
                    >
                      <template #append>积分</template></el-input
                    >
                  </el-form-item>
                </div>
              </el-form-item>
            </div>
          </div>
          <el-button type="primary" size="small" icon="Plus" @click="addReward"
            >添加连续签到规则</el-button
          >
        </el-form-item>
        <!--规则-->
        <el-form-item label="规则说明：">
          <WangEditor
            style="width: 750px"
            :content="contents"
            @contens="contentm"
            @editorContent="getEditorContent"
          ></WangEditor>
          <!-- <div class="edit_container">
            <Uediter
              :text="ueditor.text"
              :config="ueditor.config"
              ref="ue"
              @contentChange="contentChangeFunc"
            ></Uediter>
          </div> -->
        </el-form-item>
      </div>
      <!--提交-->
      <div class="common-button-wrapper">
        <el-button
          type="primary"
          size="small"
          @click="onSubmit"
          :disabled="loading"
          >提交</el-button
        >
      </div>
    </el-form>
    <GetCoupon
      v-if="open_add"
      :open_add="open_add"
      :use_type="20"
      :receiveType="2"
      @closeDialog="closeProductDialogFunc($event)"
      >选择优惠券弹出层
    </GetCoupon>
  </div>
</template>
<script>
import SignApi from "@/api/sign.js";
import GetCoupon from "@/components/coupon/GetCoupon.vue";
// import Uediter from "@/components/UE.vue";
import WangEditor from "@/components/wangEditor/index.vue";
export default {
  components: {
    /*编辑器*/
    // Uediter,
    WangEditor,
    GetCoupon,
  },
  data() {
    /*判断额外奖励*/
    let validate_reward_data = (rule, value, callback) => {
      if (value.length < 1) {
        callback(new Error("请添加至少一项额外奖励！"));
      } else {
        callback();
      }
    };

    /*连续签到天数*/
    let validate_day = (rule, value, callback) => {
      if (this.form.rewardData.length < 1) {
        callback();
      } else {
        if (value === "") {
          callback(new Error("天数不能为空！"));
        }
        callback();
      }
    };

    /*连续签到天数的积分数*/
    let validate_point = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入连续签到积分数！"));
      } else {
        callback();
      }
    };

    return {
      open_add: false,
      contents: "",
      /*富文本配置*/
      ueditor: {
        text: "",
        config: {
          initialFrameWidth: 400,
          initialFrameHeight: 500,
        },
      },
      /*表单数据对象*/
      form: {
        isOpen: false,
        isIncrease: false,
        increaseReward: 0,
        noIncrease: 0,
        everSign: 0,
        rewardData: [],
        coupon: [],
        isCoupon: true,
        signType: "",
      },
      couponList: [],
      /*是否正在加载*/
      loading: true,
      loadings: false,
      /*验证规则*/
      rules: {
        /*每日签到*/
        everSign: [
          { required: true, message: "每日签到送积分有误", trigger: "blur" },
        ],
        /*第二天起递增*/
        increaseReward: [
          {
            required: true,
            message: "请输入第二天起递增积分数",
            trigger: "blur",
          },
        ],
        /*第几天不再递增*/
        noIncrease: [
          { required: true, message: "请输入第几天不再递增", trigger: "blur" },
        ],
        /*连续签到额外奖励*/
        rewardData: [
          { validator: validate_reward_data, required: true, trigger: "blur" },
        ],
        /*连续签到*/
        day: [{ validator: validate_day, required: true, trigger: "blur" }],
        /*连续签到积分数*/
        point: [{ validator: validate_point, required: true, trigger: "blur" }],
      },
      couponName: "",
    };
  },
  created() {
    /*获取列表*/
    this.getData();
  },
  methods: {
    contentm(e) {
      this.contents = e;
    },
    getEditorContent(data) {
      console.log(data, "dtat");
      this.content = data;
    },
    addCoupon(name, index) {
      this.couponName = name;
      this.couponIndex = index;
      this.open_add = true;
    },
    /*关闭优惠券*/
    closeProductDialogFunc(e) {
      let self = this;
      self.open_add = e.openDialog;
      if (self.couponName == "coup") {
        if (e.type == "success") {
          if (self.form.coupon == null) {
            self.form.coupon = [];
          }
          console.log(self.form.coupon, "self.form.coupon");
          if (self.form.coupon.length < 1) {
            self.form.coupon.push({
              couponId: e.params.couponId,
              couponNum: 1,
            });
            self.couponList.push({
              couponId: e.params.couponId,
              name: e.params.name,
              couponNum: 1,
            });
          } else {
            let flag = true;
            self.form.coupon.forEach((item, index) => {
              if (item.couponId == e.params.couponId) {
                flag = false;
              }
            });
            if (flag) {
              self.form.coupon.push({
                couponId: e.params.couponId,
                couponNum: 1,
              });
              self.couponList.push({
                couponId: e.params.couponId,
                name: e.params.name,
                couponNum: 1,
              });
            } else {
              ElMessage.error("请勿重复添加");
            }
          }
          console.log(self.couponList);
        }
      } else if (self.couponName == "coup_sum") {
        if (e.type === "success") {
          // 确保 rewardData 中存在对应索引的 item
          const rewardItem = self.form.rewardData[self.couponIndex];
          if (rewardItem) {
            if (!Array.isArray(rewardItem.coupon)) {
              rewardItem.coupon = [];
            }
            const isDuplicate = rewardItem.coupon.some(
              (coupon) => coupon.couponId === e.params.couponId
            );
            if (!isDuplicate) {
              rewardItem.coupon.push({
                couponId: e.params.couponId,
                name: e.params.name,
                couponNum: 1,
              });
            } else {
              ElMessage.error("请勿重复添加");
            }
          } else {
            ElMessage.error("未找到对应的连续签到规则");
          }
        }
      }
    },
    delcoupon(item) {
      let self = this;
      let n = self.couponList.indexOf(item);
      self.couponList.splice(n, 1);
      self.form.coupon.splice(n, 1);
    },
    delcoupons(index, couponIndex) {
      this.form.rewardData[index].coupon.splice(couponIndex, 1);
    },
    contentChangeFunc(e) {
      this.ueditor.text = e;
    },
    /*获取列表*/
    getData() {
      let self = this;
      self.loading = true;
      SignApi.getData()
        .then((res) => {
          self.loading = false;
          let val = res.data;
          if (val.isIncrease == true) {
            self.form.isIncrease = true;
          }
          if (val.isOpen == true) {
            self.form.isOpen = true;
            self.form.increaseReward = val.increaseReward;
            self.form.noIncrease = val.noIncrease;
            self.form.everSign = val.everSign;
            self.form.coupon = JSON.parse(JSON.stringify(val.coupon));
            self.couponList = val.coupon;
            self.form.signType = val.signType;
            self.contents = val.content;
            // self.ueditor.text = val.content;
            if (val.rewardData) {
              let len = val.rewardData.length;
              for (let i = 0; i < len; i++) {
                let item = val.rewardData[i];
                if (item.isCoupon == true) {
                  item.isCoupon = true;
                } else {
                  item.isCoupon = false;
                }
                if (item.isPoint == true) {
                  item.isPoint = true;
                } else {
                  item.isPoint = false;
                }
              }
              self.form.rewardData = val.rewardData;
            }
          }
          setTimeout(() => {
            self.loadings = true;
          }, 1000);
        })
        .catch((error) => {
          self.loading = false;
        });
    },

    /*提交签到有礼*/
    onSubmit() {
      let self = this;
      let params = self.form;
      params.coupon = self.couponList;
      if (params.isOpen) {
        params.content = self.contents;
      }
      self.loading = true;
      console.log(params, "params");
      self.$refs.ruleForm.validate((valid) => {
        if (valid) {
          SignApi.saveData(params, true)
            .then((data) => {
              ElMessage({
                message: "恭喜你，保存成功",
                type: "success",
              });
              self.getData();
            })
            .catch((error) => {
              self.loading = false;
            });
        }
      });
    },

    /*获取富文本编辑器的内容*/
    getContent: function () {
      return this.$refs.ue.getUEContent();
    },

    addReward() {
      let obj = {
        day: 0,
        isPoint: false,
        point: 0,
        isCoupon: false,
        coupon: [],
      };
      this.form.rewardData.push(obj);
    },

    deleteRewardClick(e) {
      this.form.rewardData.splice(e, 1);
    },
  },
};
</script>

<style scoped="scoped">
.open-sign {
  margin-left: 100px;
  margin-bottom: 10px;
  margin-top: -20px;
}

.reward-list .reward-item {
  margin-bottom: 10px;
  padding: 20px 20px 0;
  background-color: rgba(246, 246, 246, 1);
}

.reward-list .delete-reward {
  position: absolute;
  top: 10px;
  right: 10px;
  cursor: pointer;
  z-index: 10;
}
.el-button--small.is-circle {
  padding: 4px;
}
.bg_coupon {
  background-color: rgba(246, 246, 246, 1);
  color: rgba(16, 16, 16, 1);
  font-size: 14px;
  padding: 10px;
}
</style>
